package com.itboye.ihomebank.home;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import java.util.Observable;
import java.util.Observer;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.itboye.ihomebank.R;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.bean.AvatarDataBeans;
import com.itboye.ihomebank.presenter.HousePresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.CameraPopupWindow;
import com.itboye.ihomebank.util.ImageCompress;
import com.itboye.ihomebank.util.UploadImage;
import com.itboye.ihomebank.util.UploadImage.OnUploadlistener;
import com.itboye.ihomebank.util.XImageLoader;

/**
 * 名片认证
 * 
 */
public class ActivityCardRenZheng extends BaseOtherActivity implements
		Observer, OnUploadlistener {
	private ImageView close_icon;// 返回图片
	private TextView add_shap_title_tv;// 标题

	ImageView card_img;
	EditText card_yzm;
	TextView card_huoqu;
	TextView card_tijiao;
	private CameraPopupWindow cameraPopupWindow;
	private Uri fileUri;
	private String picture_name;
	private String fileName;
	public static final int MEDIA_TYPE_IMAGE = 1;
	HousePresenter housePresenter;
	private int REAL_PHONE_TWO = 111;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.close_icon:
			finish();
			break;
		case R.id.card_tijiao:// 提交照片
			UploadImage.getInstance().execute(
					new String[] { card_img.getTag() + "" }, "broker", this,
					null);
			break;
		case R.id.card_img:
			cameraPopupWindow = new CameraPopupWindow(this, this);
			cameraPopupWindow.showAtLocation(v, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);
			break;
		case R.id.open_camera:
			/**
			 * 打开照相机
			 */
			picture_name = android.text.format.DateFormat.format(
					"yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))
					+ ".jpg";
			File file = new File("/sdcard/Image/");
			file.mkdirs();// 创建文件夹
			fileName = "/sdcard/Image/" + picture_name;
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_OUTPUT,
					Uri.fromFile(new File(fileName)));
			startActivityForResult(intent, Activity.DEFAULT_KEYS_DIALER);
			cameraPopupWindow.dismiss();
			break;
		case R.id.pick_image:
			Intent intent2 = new Intent();
			intent2.setType("image/*");// 可选择图片视频
			// 修改为以下两句代码
			intent2.setAction(Intent.ACTION_PICK);
			intent2.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);// 使用以上这种模式，并添加以上两
			startActivityForResult(intent2, REAL_PHONE_TWO);

			break;
		default:
			break;
		}
	}

	@Override
	protected int layout_id() {
		// TODO Auto-generated method stub
		return R.layout.activity_card_ren_zheng;
	}

	@Override
	protected void onInitController() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onInit() {
		// TODO Auto-generated method stub

		add_shap_title_tv.setText("名片认证");
		housePresenter = new HousePresenter(this);
	}

	@Override
	protected void onReadIntent(Bundle bundle) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK
				&& requestCode == Activity.DEFAULT_KEYS_DIALER) {
			Bitmap bit = BitmapFactory.decodeFile(fileName);
			int degree = ImageCompress.readPictureDegree(fileName);
			if (degree <= 0) {
				// show_Image.setImageBitmap(bm);
			} else {
				// 创建操作图片是用的matrix对象
				Matrix matrix = new Matrix();
				// 旋转图片动作
				matrix.postRotate(degree);
				// 创建新图片
				bit = Bitmap.createBitmap(bit, 0, 0, bit.getWidth(),
						bit.getHeight(), matrix, true);
			}
			bit=zoomImg(bit,450,500);
			saveImage(bit, new File(fileName));
		} 
		if (requestCode == REAL_PHONE_TWO && resultCode==RESULT_OK) { // 相册
			Uri selectedImage04 = data.getData();
			String innerUrl = getRealPathFromURI(selectedImage04);

			Bitmap bt04 = BitmapFactory.decodeFile(innerUrl);
			XImageLoader.load("file://" + innerUrl, card_img);
			cameraPopupWindow.dismiss();
		}
	}
	
	/**  
	 *  处理图片   
	 * @param bm 所要转换的bitmap  
	 * @param newWidth新的宽  
	 * @param newHeight新的高    
	 * @return 指定宽高的bitmap  
	 */  
	 public static Bitmap zoomImg(Bitmap bm, int newWidth ,int newHeight){    
	    // 获得图片的宽高    
	    int width = bm.getWidth();    
	    int height = bm.getHeight();    
	    // 计算缩放比例    
	    float scaleWidth = ((float) newWidth) / width;    
	    float scaleHeight = ((float) newHeight) / height;    
	    // 取得想要缩放的matrix参数    
	    Matrix matrix = new Matrix();    
	    matrix.postScale(scaleWidth, scaleHeight);    
	    // 得到新的图片    
	    Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);    
	    return newbm;    
	} 

	
	/**
	 * 该方法用于获取文件的真实路径从URI 从相机拍摄
	 */
	private String getRealPathFromURI(Uri contentUri) {
		try {
			String[] proj = { MediaStore.Images.Media.DATA };
			Cursor cursor = this.managedQuery(contentUri, proj, null, null,
					null);
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} catch (Exception e) {
			return contentUri.getPath();
		}
	}
	
	public void saveImage(Bitmap data, File fileName) {
		String sdStatus = Environment.getExternalStorageState();
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
			Log.i("TestFile", "SD card is not avaiable/writeable right now.");
			return;
		}
		if (fileName.exists()) {
			fileName.delete();
		}
		FileOutputStream b = null;
		try {
			b = new FileOutputStream(fileName);
			data.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				b.flush();
				b.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		String path=fileName.getAbsolutePath();
		Bitmap bitmap=BitmapFactory.decodeFile(path);
		System.out.println(bitmap.getWidth()+"::"+bitmap.getHeight());
		card_img.setTag(fileName);
		XImageLoader.load("file://" + fileName, card_img);

	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub

	}

	@Override
	public void OnSuccess(ArrayList<AvatarDataBeans> resultData) {
		// TODO Auto-generated method stub
		ByAlert.alert("申请已提交,请等待审核...");
		finish();
	}

	@Override
	public void OnError(String resultData) {
		// TODO Auto-generated method stub
		ByAlert.alert(resultData);
	}

}
